<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Order, Goods};
use think\Db;
use think\facade\Log;

class Orders extends Command
{
    protected function configure()
    {
        $this->setName('Orders')->setDescription('订单自动取消、确认');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        //刷单
        // $goods = (new Goods())->where('shopid', 1)->select();
        // foreach ($goods as $good) {
        //     $number = rand(500, 1000);
        //     (new Goods())->where('id', $good['id'])->update(['sale' => $number]);
        // }
        //自动取消订单
        $time = date('Y-m-d H:i:s', time() - 600);
        $list = (new Order())->where(['status' => 1])->where('created', '<=', $time)->select();
        foreach ($list as $lists) {
            Db::startTrans();
            try {
                (new Order())->order_status($lists, 5);
                echo '自动取消' . $lists['id'];
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
        }
        //自动完成订单
        $times = date('Y-m-d H:i:s', time() - 86400);
        $list = (new Order())->where(['status' => 3])->where('distime', '<=', $time)->select();
        foreach ($list as $lists) {
            Db::startTrans();
            try {
                (new Order())->order_status($lists, 4);
                echo '自动完结' . $lists['id'];
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
        }
    }
}